package com.tiance.web.controller.back;

import com.alibaba.fastjson.JSON;
import com.tiance.constants.CommonConstants;
import com.tiance.dal.dataobject.ActivityDO;
import com.tiance.dal.dataobject.MemberAuthenticationInfoDO;
import com.tiance.dal.dataobject.UserDO;
import com.tiance.domainservice.checker.ActivityChecker;
import com.tiance.domainservice.checker.MemberParamsChecker;
import com.tiance.domainservice.domain.ActivityDomain;
import com.tiance.domainservice.domain.MemberAuthenticationInfoDomain;
import com.tiance.domainservice.service.ActivityService;
import com.tiance.enums.*;
import com.tiance.exception.BusinessException;
import com.tiance.integration.cache.MapCacheUtil;
import com.tiance.page.QueryPage;
import com.tiance.utils.BeanConverterUtil;
import com.tiance.utils.Validator;
import com.tiance.vo.ActivityVO;
import com.tiance.web.aspect.OperatorControllerLog;
import com.tiance.web.controller.base.BackController;
import com.tiance.web.controller.base.FrontController;
import com.tiance.web.controller.common.BaseResponse;
import com.tiance.web.convertor.ModelConvert;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Arrays;
import java.util.List;

/**
 *
 * @author 雷霆
 * @version 1.0.0
 * @date$ 2019/1/30
 *
 * Description：活动管理
 *
 * Modification History:
 *
 */
@Controller
@RequestMapping(value = "/back/activity")
public class BackActivityController extends BackController {

    private static String LOG_PREFIX ="BackActivityController| 活动控制器===>";

    @Autowired
    private ActivityService activityService;


    @RequestMapping(value = "/toPublishedActivityList.action",method = RequestMethod.GET)
    @RequiresPermissions("menu:content:activity")
    @OperatorControllerLog(operationLogType= OperateTypeEnum.FRONT_INTERFACE,operationName="跳转到已发布活动列表页面")
    public String toPublishedActivityList() {
        return "/back/content/activity/publishedActivityList";
    }

    @RequestMapping(value = "/toApplyActivityList.action",method = RequestMethod.GET)
    @RequiresPermissions("menu:content:activity")
    @OperatorControllerLog(operationLogType= OperateTypeEnum.FRONT_INTERFACE,operationName="跳转到活动列表页面")
    public String toApplyActivityList() {
        return "/back/content/activity/activityApplyList";
    }





    @RequestMapping(value = "/addActivity.action",method = RequestMethod.POST)
    @OperatorControllerLog(operationLogType= OperateTypeEnum.FRONT_INTERFACE,operationName="插入活动")
    public String addActivity(HttpServletRequest request, Model model, ActivityVO activityVO){
        logger.info("开始插入活动，请求参数:{}", JSON.toJSONString(activityVO));
        try {

            Session session = SecurityUtils.getSubject().getSession();
            UserDO userDO=(UserDO)session.getAttribute(CommonConstants.USER);
            activityVO.setApplicantId(userDO.getId());
            activityVO.setApplicantType(ApplicantTypeEnum.SYSTEM.getCode());
            ActivityChecker.checkAddActivity(activityVO);
            ActivityDomain activityDomain= ModelConvert.activityVO2ActivityDomain(activityVO);
            activityService.addActivity(activityDomain);
        }catch(BusinessException e1){
            logger.info(LOG_PREFIX+"插入活动失败，失败原因：",e1);
            activityVO.setErrorInfo(e1.getMessage());
            return  "/views/initFail";
        }catch (Exception e2){
            activityVO.setErrorInfo("插入活动失败,请稍后重试!");
            logger.error(LOG_PREFIX+"插入活动失败,失败原因",e2);
            return "/views/initFail";
        }
        logger.info("结束插入活动，返回数据:{}", model);
        return  "/views/initFail";

    }


    @RequestMapping(value = "/queryActivityDetailById.action",method = RequestMethod.POST)
    @ResponseBody
    @OperatorControllerLog(operationLogType=OperateTypeEnum.FRONT_INTERFACE,operationName="查询活动详情")
    public BaseResponse queryActivityDetailById(ActivityVO activityVO){
        logger.info("开始查询活动详情，请求参数:{}", JSON.toJSONString(activityVO));

        BaseResponse<ActivityDO> backResponse=new BaseResponse<>();
        try {

            ActivityChecker.checkId(activityVO.getId());
            ActivityDomain activityDomain= ModelConvert.activityVO2ActivityDomain(activityVO);
            ActivityDO activityDO= activityService.queryActivityDetailById(activityDomain);
            backResponse.setResult(activityDO);
            backResponse.setResponseCode(ErrorCodeEnum.SUCCESS.getCode());
            backResponse.setSuccess(true);
        }catch(BusinessException e1){
            logger.info(LOG_PREFIX+"查询活动详情失败，失败原因：",e1);
            backResponse.setSuccess(false);
            backResponse.setMessage(e1.getMessage());
        }catch (Exception e2){
            logger.error(LOG_PREFIX+"查询活动详情失败,失败原因",e2);
            backResponse.setSuccess(false);
            backResponse.setMessage("查询活动详情失败");
        }
        logger.info("结束查询活动详情，返回数据:{}", JSON.toJSONString(backResponse));
        return  backResponse;

    }


    @RequestMapping(value = "/queryApplyActivityList.action",method = RequestMethod.POST)
    @ResponseBody
    @OperatorControllerLog(operationLogType=OperateTypeEnum.FRONT_INTERFACE,operationName="查询会员申请的活动")
    public BaseResponse queryApplyActivityList(ActivityVO activityVO, QueryPage queryPage){
        logger.info("开始查询活动列表，请求参数:{}", JSON.toJSONString(activityVO));

        BaseResponse<ActivityDO> backResponse=new BaseResponse<>();
        try {
            MemberParamsChecker.checkPageQuery(queryPage);
            activityVO.setQueryPage(queryPage);

            List<String> status = Arrays.asList(ActivityStatusEnum.UN_AUDIT.getCode());
            activityVO.setStatusScope(status);
            ActivityDomain activityDomain= ModelConvert.activityVO2ActivityDomain(activityVO);
            List<ActivityDO> applyActivityList= activityService.queryApplyActivity(activityDomain);
            backResponse.setResultList(applyActivityList);
            backResponse.setQueryPage(activityDomain.getQueryPage());
            backResponse.setTotalRecord(applyActivityList.size());
            backResponse.setResponseCode(ErrorCodeEnum.SUCCESS.getCode());
            backResponse.setSuccess(true);
        }catch(BusinessException e1){
            logger.info(LOG_PREFIX+"查询活动列表失败，失败原因：",e1);
            backResponse.setSuccess(false);
            backResponse.setMessage(e1.getMessage());
        }catch (Exception e2){
            logger.error(LOG_PREFIX+"查询活动列表失败,失败原因",e2);
            backResponse.setSuccess(false);
            backResponse.setMessage("查询活动列表失败");
        }
        logger.info("结束查询活动列表，返回数据:{}", JSON.toJSONString(backResponse));
        return  backResponse;

    }



    @RequestMapping(value = "/queryPublishedActivityList.action",method = RequestMethod.POST)
    @ResponseBody
    @OperatorControllerLog(operationLogType=OperateTypeEnum.FRONT_INTERFACE,operationName="查询已发布会员申请的活动")
    public BaseResponse queryPublishedActivityList(ActivityVO activityVO, QueryPage queryPage){
        logger.info("开始查询活动列表，请求参数:{}", JSON.toJSONString(activityVO));

        BaseResponse<ActivityDO> backResponse=new BaseResponse<>();
        try {
            MemberParamsChecker.checkPageQuery(queryPage);
            activityVO.setQueryPage(queryPage);

            ActivityDomain activityDomain= ModelConvert.activityVO2ActivityDomain(activityVO);
            List<ActivityDO> applyActivityList= activityService.queryApplyActivity(activityDomain);
            backResponse.setResultList(applyActivityList);
            backResponse.setQueryPage(activityDomain.getQueryPage());
            backResponse.setTotalRecord(applyActivityList.size());
            backResponse.setResponseCode(ErrorCodeEnum.SUCCESS.getCode());
            backResponse.setSuccess(true);
        }catch(BusinessException e1){
            logger.info(LOG_PREFIX+"查询活动列表失败，失败原因：",e1);
            backResponse.setSuccess(false);
            backResponse.setMessage(e1.getMessage());
        }catch (Exception e2){
            logger.error(LOG_PREFIX+"查询活动列表失败,失败原因",e2);
            backResponse.setSuccess(false);
            backResponse.setMessage("查询活动列表失败");
        }
        logger.info("结束查询活动列表，返回数据:{}", JSON.toJSONString(backResponse));
        return  backResponse;

    }





    @RequestMapping(value = "/cancelActivity.action",method = RequestMethod.POST)
    @ResponseBody
    @OperatorControllerLog(operationLogType= OperateTypeEnum.FRONT_INTERFACE,operationName="取消活动")
    public BaseResponse cancelActivity( ActivityVO activityVO){
        logger.info("开始取消活动，请求参数:{}", JSON.toJSONString(activityVO));
        BaseResponse backResponse=new BaseResponse<>();

        try {
            Validator.assertNull(activityVO.getId(),"活动ID不能为空!");
            ActivityDomain activityDomain= ModelConvert.activityVO2ActivityDomain(activityVO);
            activityDomain.setActivityStatus(ActivityStatusEnum.ACTIVITY_CANCEL.getCode());
            if(MapCacheUtil.lock(activityVO.getId()+ EntityTypeEnum.ACTIVITY.getCode())) {
                activityService.cancel(activityDomain);
            }else {
                throw new BusinessException("该活动正在操作中，请稍后再试!");
            }
            backResponse.setSuccess(true);
            backResponse.setResponseCode(ErrorCodeEnum.SUCCESS.getCode());
        }catch(BusinessException e1){
            logger.info(LOG_PREFIX+"取消活动失败，失败原因：",e1);
            backResponse.setSuccess(false);
            backResponse.setMessage(e1.getMessage());
        }catch (Exception e2){
            logger.error(LOG_PREFIX+"取消活动失败,失败原因",e2);
            backResponse.setSuccess(false);
            backResponse.setMessage("取消活动失败");
        }finally {
            MapCacheUtil.unlock(activityVO.getId() + EntityTypeEnum.ACTIVITY.getCode());
        }
        logger.info("结束取消活动，返回数据:{}", JSON.toJSONString(backResponse));
        return  backResponse;

    }


    @RequestMapping(value = "/finishActivity.action",method = RequestMethod.POST)
    @ResponseBody
    @OperatorControllerLog(operationLogType= OperateTypeEnum.FRONT_INTERFACE,operationName="结束活动")
    public BaseResponse finishActivity( ActivityVO activityVO){
        logger.info("开始结束活动，请求参数:{}", JSON.toJSONString(activityVO));
        BaseResponse backResponse=new BaseResponse<>();

        try {
            Validator.assertNull(activityVO.getId(),"活动ID不能为空!");
            ActivityDomain activityDomain= ModelConvert.activityVO2ActivityDomain(activityVO);
            if(MapCacheUtil.lock(activityVO.getId()+ EntityTypeEnum.ACTIVITY.getCode())) {
                activityService.finish(activityDomain);
            }else {
                throw new BusinessException("该活动正在操作中，请稍后再试!");
            }
            backResponse.setSuccess(true);
            backResponse.setResponseCode(ErrorCodeEnum.SUCCESS.getCode());
        }catch(BusinessException e1){
            logger.info(LOG_PREFIX+"结束活动失败，失败原因：",e1);
            backResponse.setSuccess(false);
            backResponse.setMessage(e1.getMessage());
        }catch (Exception e2){
            logger.error(LOG_PREFIX+"结束活动失败,失败原因",e2);
            backResponse.setSuccess(false);
            backResponse.setMessage("结束活动失败");
        }finally {
            MapCacheUtil.unlock(activityVO.getId()+ EntityTypeEnum.ACTIVITY.getCode());
        }
        logger.info("结束活动，返回数据:{}", JSON.toJSONString(backResponse));
        return  backResponse;

    }

}